<template>
    <div id="user-main">
        <div class="userList-herd">
            <div>
                <el-form :inline="true" :model="paging" class="demo-form-inline">
                    <el-form-item v-for="(item, index) in menuBtns" :key="index">
                        <el-button v-if="item.icon == CREATE || item.icon == DELETE" :type="item.icon"
                            @click="clickBtn(item.icon)"> {{ item.menuName }}</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="paging.name" placeholder="资源名称"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="paging.modelName" placeholder="请选择模块名称">
                            <el-option v-for="(item, index) in modelOptions" :key="index" :label="item.name"
                                :value="item.name">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="onReSetSeach">重置</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="init">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <div class="user-body">
            <el-table ref="multipleTable" tooltip-effect="dark" @selection-change="handleSelectionChange"
                :data="pagingData.totalList" style="width: 100%">
                <el-table-column type="selection" width="55" :selectable="checkboxInit"> </el-table-column>
                <el-table-column prop="id" label="id" width="100" align="center"></el-table-column>
                <el-table-column prop="name" label="资源名称" width="180" align="center"></el-table-column>
                <el-table-column prop="modelName" label="模块名称" width="180" align="center"></el-table-column>
                <el-table-column prop="perms" label="请求标识" width="180" align="center"></el-table-column>
                <el-table-column prop="requestUri" label="请求路径" width="180" align="center"></el-table-column>
                <el-table-column prop="isDel" label="是否开启" width="180" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="!scope.row.isDel" type="success">开启</el-tag>
                        <el-tag v-else type="info">关闭</el-tag>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="120" align="center">
                    <template slot-scope="scope">
                        <div v-if="isSysDef(userInfo.userType) && !isSysDef(scope.row.resourceType)">
                            <div class="btns" v-for="(item, index) in menuBtns" :key="index">
                                <el-button type="text" size="small" v-if="item.icon == UPDATE || item.icon == DELETE"
                                    @click="handleClick(item.icon, scope.row)" :style="getButtonStyle(item.icon)">{{
                                        item.menuName }}</el-button>
                            </div>
                        </div>
                        <div v-if="!isSysDef(userInfo.userType) && scope.row.resourceType == '01'">
                            <div class="btns" v-for="(item, index) in menuBtns" :key="index">
                                <el-button type="text" size="small" v-if="item.icon == UPDATE || item.icon == DELETE"
                                    @click="handleClick(item.icon, scope.row)" :style="getButtonStyle(item.icon)">{{
                                        item.menuName }}</el-button>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div v-if="pagingData && pagingData.totalList && pagingData.totalList.length > 0">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pagingData.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper" :total="pagingData.total">
                </el-pagination>
            </div>
        </div>

        <el-dialog title="添加权限资源" :visible.sync="dialogTableAddVisible">
            <el-form :model="addForm" ref="addForm">
                <el-form-item label="模块id" prop="modelId" :label-width="formLabelWidth" :required="true">
                    <el-select v-model="addForm.modelId" placeholder="请选择模块名称">
                        <el-option v-for="(item, index) in modelOptions" :key="index" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="资源名称" prop="name" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="addForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="请求标识" prop="perms" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="addForm.perms" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="请求路径" prop="requestUri" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="addForm.requestUri" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="onSave">保存</el-button>
            </div>
        </el-dialog>

        <el-dialog title="编辑权限资源" :visible.sync="dialogTableEditVisible">
            <el-form :model="editForm" ref="editForm">
                <el-form-item label="模块id" prop="modelId" :label-width="formLabelWidth" :required="true">
                    <el-select v-model="editForm.modelId" placeholder="请选择模块名称">
                        <el-option v-for="(item, index) in modelOptions" :key="index" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="资源名称" prop="name" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="editForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="请求标识" prop="perms" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="editForm.perms" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="请求路径" prop="requestUri" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="editForm.requestUri" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="是否开启" :label-width="formLabelWidth">
                    <el-switch v-model="editForm.isDel" active-color="#13ce66" inactive-color="#ff4949" :active-value="0"
                        :inactive-value="1">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="onEdit">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>
  
<script>
import { mapState } from 'vuex';
import { getSecondStr, isSysDef } from "@/common/utils/strUtil";
import { menuBtnByParentId } from "@/common/utils/MenuBtnUtils";
import { resourcesListPaging, createResources, deleteResources, updateResources } from "@/common/api/resources";
import { modelListPaging } from "@/common/api/model";
import { dateTimeInMilliseconds } from "@/common/utils/formatTime";
import { CREATE, UPDATE, DELETE, UNBIND, BIND } from "@/common/constant/Const";
export default {
    components: {
    },
    data() {
        return {
            CREATE,
            UPDATE,
            DELETE,
            UNBIND,
            BIND,
            menuBtns: [],
            paging: {
                currentPage: 1,
                pageSize: 10,
            },
            pagingData: {},
            dialogTableAddVisible: false,
            addForm: {
            },
            formLabelWidth: "120px",
            dialogTableEditVisible: false,
            editForm: {},
            deleteForm: {
                ids: [],
            },
            unBind: {},
            dialogTableBindVisible: false,
            bind: {
                roleIds: [],
            },
            roleListData: [],
            viewKey: {
                authEndTime: null,
            },
            dialogTableBindVisibleKey: false,
            eidtDeptDisPlay: false,

            modelOptions: []
        };
    },
    computed: {
        ...mapState({
            menuItem: state => state.tab.menuItem,
            // isSelectedDept: state => state.tab.isSelectedDept,
            userInfo: state => state.tab.userInfo,
        }),
    },
    mounted() {
        this.getMenuBtn(this.menuItem.id);
        this.init();
        modelListPaging({
            currentPage: 1,
            pageSize: 100,
        }).then((resp) => {
            if (resp) {
                this.modelOptions = resp.data.totalList.filter((item => item.isDel !== 1))
            }
        });
    },
    methods: {
        getSecondStr,
        isSysDef,
        menuBtnByParentId,
        dateTimeInMilliseconds,
        getMenuBtn(data) {
            menuBtnByParentId(data).then((respData) => {
                this.menuBtns = respData;
            }).catch((error) => {
                console.error("Error fetching menu buttons:", error);
            });
        },
        // 查询数据
        init() {
            resourcesListPaging(this.paging).then((resp) => {
                if (resp) {
                    this.pagingData = resp.data;
                }
            });
        },
        clickBtn(data) {
            console.log(data);
            if (CREATE == data) {
                this.dialogTableAddVisible = true;
            }
            if (UPDATE == data) {
            }
            if (DELETE == data) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.onRemove();
                }).catch(() => {
                    this.deleteForm.ids = [];
                    this.$refs.multipleTable.clearSelection();
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        onRemove() {
            deleteResources(this.deleteForm).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                }
            })
        },
        // 重置
        onReSetSeach() {
            this.paging = {
                currentPage: 1,
                pageSize: 10,
            };
            this.init();
        },
        // 分页回调
        handleSizeChange(val) {
            this.paging.pageSize = val;
            this.init()
        },
        // 分页回调
        handleCurrentChange(val) {
            this.paging.currentPage = val;
            this.init()
        },
        // 多选表时的回调
        handleSelectionChange(val) {
            this.deleteForm.ids = val.map(item => item.id);
        },
        // 是否可选择表格
        checkboxInit(row, index) {
            if (isSysDef(this.userInfo.resourceType)) {
                return !isSysDef(row.resourceType);
            }
            return row.resourceType == '01';
        },
        // 同意取消
        handleCancel() {
            this.dialogTableAddVisible = false;
            this.addForm = {
            };

            this.dialogTableEditVisible = false;
            this.editForm = {};
            this.deleteForm.ids = [];
            this.unBind = {};
            this.dialogTableBindVisible = false;
            this.bind = { roleIds: [] };

            this.viewKey = {
                authEndTime: null,
            };
            this.dialogTableBindVisibleKey = false;
            // this.$refs.selectedDept.reSetDef();
            this.eidtDeptDisPlay = false;
        },
        // 新增用户
        onSave() {
            // this.addForm.deptId = this.isSelectedDept.id == '' ? null : this.isSelectedDept.id;
            createResources(this.addForm).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                }
            });
        },
        // 检查是否需要应用红色字体
        getButtonStyle(perms) {
            if (this.DELETE == perms) {
                return { color: 'red' };
            }
            if (this.UNBIND == perms) {
                return { color: '#E6A23C' };
            }
            // 默认样式（可以是空对象，或者你可以设置其他样式）
            return {};
        },
        // 点击事件
        handleClick(type, data) {
            if (this.UPDATE == type) {
                this.editForm = { ...data };
                this.dialogTableEditVisible = true;
            }
            if (this.DELETE == type) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deleteForm.ids.push(data.id);
                    this.onRemove();
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        // 修改保存
        onEdit() {
            // this.editForm.deptId = this.isSelectedDept.id == '' ? -1 : this.isSelectedDept.id;
            updateResources(this.editForm).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                }
            });
        },
    },
};
</script>
<style lang="less" scoped>
#user-main::v-deep {
    .el-select {
        width: 100%;
    }
}
</style>